package com.jctrip.hotel.source.xxl.rezen.thread;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.jctrip.hotel.common.constant.RedisKeyConstant;
import com.jctrip.hotel.common.context.BeanContext;
import com.jctrip.hotel.common.util.RedisUtil;
import com.jctrip.hotel.source.service.rezen.RezenService;
import com.jctrip.hotel.source.service.rezen.RezenTaskService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author henry
 * @Date 2023/8/12 15:54
 * @Description
 */
@Slf4j
public class SyncRezenRatesPullThread implements Runnable {
    private final String secretId;
    private final String secretKey;
    private final Long groupId;
    private final Long productId;
    private final Integer days;

    public SyncRezenRatesPullThread(String secretId, String secretKey, Long groupId, Long productId, Integer days) {
        this.secretId = secretId;
        this.secretKey = secretKey;
        this.groupId = groupId;
        this.productId = productId;
        this.days = days;
    }

    @Override
    public void run() {
        RedisUtil redisUtil = BeanContext.getApplicationContext().getBean(RedisUtil.class);
        RezenTaskService rezenTaskService = BeanContext.getApplicationContext().getBean(RezenTaskService.class);
        RezenService rezenService = BeanContext.getApplicationContext().getBean(RezenService.class);

        while (redisUtil.lGetListSize(RedisKeyConstant.HOTEL_MAIN_REZEN_RATES_LIST) > 0) {
            try {
                String hotelId = (String) redisUtil.rightPop(RedisKeyConstant.HOTEL_MAIN_REZEN_RATES_LIST);
                if (StringUtils.isBlank(hotelId)) {
                    continue;
                }
                Date start = new Date();
                Date end = DateUtils.addDays(start, days);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                rezenTaskService.syncRezenRatesTaskPop(secretId, secretKey, groupId,
                        rezenService.parseHotelId(hotelId), productId,
                        simpleDateFormat.format(start), simpleDateFormat.format(end));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
